<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';

const props = defineProps<{
  isVisible: boolean;
  content: string;
}>();

const emit = defineEmits<{
  close: [];
  save: [content: string];
}>();

const editorContent = ref('');
const editorRef = ref<HTMLDivElement | null>(null);

// 监听内容变化
watch(() => props.content, (newContent) => {
  if (newContent) {
    editorContent.value = newContent;
    
    // 确保编辑器DOM已更新后设置内容
    setTimeout(() => {
      if (editorRef.value) {
        editorRef.value.innerHTML = newContent;
      }
    }, 0);
  }
}, { immediate: true });

// 监听可见性变化
watch(() => props.isVisible, (visible) => {
  if (visible && editorRef.value) {
    // 当编辑器显示时，设置内容并聚焦
    editorRef.value.innerHTML = editorContent.value;
    setTimeout(() => {
      editorRef.value?.focus();
    }, 100);
  }
});

// 关闭编辑器
const closeEditor = () => {
  emit('close');
};

// 设置编辑器可编辑
onMounted(() => {
  if (editorRef.value) {
    editorRef.value.contentEditable = 'true';
  }
});

// 工具栏功能
const execCommand = (command: string, value?: string) => {
  try {
    // 确保编辑器存在且可编辑
    if (!editorRef.value) {
    console.warn('Editor reference not found');
    return;
    }

    // 保存当前选区
    const selection = window.getSelection();
    const range = selection?.getRangeAt(0);

    // 确保编辑器有焦点
    editorRef.value.focus();

    // 如果有保存的选区，恢复它
    if (selection && range) {
    selection.removeAllRanges();
    selection.addRange(range);
    }

    // 确保命令可用（兼容旧版和新版）
    const isCommandSupported = (() => {
    if (typeof document.queryCommandSupported === 'function') {
        return document.queryCommandSupported(command);
    }
    // 如果不支持 queryCommandSupported，假设命令可用（保守策略）
    return true;
    })();

    if (isCommandSupported) {
    // 处理 value 为 null 的情况
    const execValue = value ?? undefined; // 将 null 转换为 undefined
    // 执行命令（兼容旧版）
    if (typeof document.execCommand === 'function') {
        document.execCommand(command, false, execValue);
    } else {
        console.warn(`execCommand is not supported in this environment`);
    }
    } else {
    console.warn(`Command ${command} is not supported`);
    }
    // 重新聚焦编辑器
    editorRef.value.focus();
  } catch (error) {
    console.error(`Error executing command ${command}:`, error);
  }
};

const formatBold = () => execCommand('bold');
const formatItalic = () => execCommand('italic');
const formatUnderline = () => execCommand('underline');
const formatStrikeThrough = () => execCommand('strikeThrough');
const formatHeading = (level: number) => execCommand('formatBlock', `h${level}`);
const formatParagraph = () => execCommand('formatBlock', 'p');
const formatOrderedList = () => execCommand('insertOrderedList');
const formatUnorderedList = () => execCommand('insertUnorderedList');
const formatIndent = () => execCommand('indent');
const formatOutdent = () => execCommand('outdent');
const formatAlignLeft = () => execCommand('justifyLeft');
const formatAlignCenter = () => execCommand('justifyCenter');
const formatAlignRight = () => execCommand('justifyRight');
const formatAlignJustify = () => execCommand('justifyFull');
const insertLink = () => {
  const url = prompt('输入链接URL:', 'http://');
  if (url && url.trim()) {
    execCommand('createLink', url.trim());
  }
};
const removeFormat = () => execCommand('removeFormat');

// 导出PDF功能
const exportToPDF = async () => {
  if (!editorRef.value) return;
  
  try {
    // 创建canvas
    const canvas = await html2canvas(editorRef.value, {
      scale: 2,
      useCORS: true,
      logging: false
    });

    // 创建PDF
    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: 'a4'
    });

    // 获取图像数据
    const imgData = canvas.toDataURL('image/jpeg', 1.0);
    
    // 获取页面尺寸
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();
    
    // 计算图像尺寸以适应页面宽度
    const imgWidth = pageWidth;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;
    
    let heightLeft = imgHeight;
    let position = 0;
    
    // 添加第一页
    pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;
    
    // 如果内容超过一页，添加新页面
    while (heightLeft >= 0) {
      position = heightLeft - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
    }
    
    // 保存PDF
    pdf.save('editor-content.pdf');
  } catch (error) {
    console.error('Error exporting to PDF:', error);
  }
};
</script>

<template>
  <div class="editor-container" :class="{ 'visible': isVisible }">
    <div class="editor-header">
      <h2>富文本编辑器</h2>
      <button class="close-btn" @click="closeEditor">&times;</button>
    </div>
    
    <div class="toolbar">
      <div class="toolbar-group">
        <button title="粗体" @click="formatBold">
          <i class="format-icon bold">B</i>
        </button>
        <button title="斜体" @click="formatItalic">
          <i class="format-icon italic">I</i>
        </button>
        <button title="下划线" @click="formatUnderline">
          <i class="format-icon underline">U</i>
        </button>
        <button title="删除线" @click="formatStrikeThrough">
          <i class="format-icon strikethrough">S</i>
        </button>
      </div>
      
      <div class="toolbar-group">
        <button title="标题1" @click="formatHeading(1)">H1</button>
        <button title="标题2" @click="formatHeading(2)">H2</button>
        <button title="标题3" @click="formatHeading(3)">H3</button>
        <button title="段落" @click="formatParagraph">P</button>
      </div>
      
      <div class="toolbar-group">
        <button title="有序列表" @click="formatOrderedList">
          <i class="format-icon">1.</i>
        </button>
        <button title="无序列表" @click="formatUnorderedList">
          <i class="format-icon">•</i>
        </button>
        <button title="增加缩进" @click="formatIndent">
          <i class="format-icon">→</i>
        </button>
        <button title="减少缩进" @click="formatOutdent">
          <i class="format-icon">←</i>
        </button>
      </div>
      
      <div class="toolbar-group">
        <button title="左对齐" @click="formatAlignLeft">
          <i class="format-icon">⟵</i>
        </button>
        <button title="居中" @click="formatAlignCenter">
          <i class="format-icon">⟷</i>
        </button>
        <button title="右对齐" @click="formatAlignRight">
          <i class="format-icon">⟶</i>
        </button>
        <button title="两端对齐" @click="formatAlignJustify">
          <i class="format-icon">≡</i>
        </button>
      </div>
      
      <div class="toolbar-group">
        <button title="插入链接" @click="insertLink">
          <i class="format-icon">🔗</i>
        </button>
        <button title="清除格式" @click="removeFormat">
          <i class="format-icon">✕</i>
        </button>
      </div>

      <div class="toolbar-group">
        <button title="导出PDF" @click="exportToPDF">
          <i class="format-icon">📄</i>
        </button>
      </div>
    </div>
    
    <div class="editor-content-wrapper">
      <div 
        ref="editorRef" 
        class="editor-content markdown-body"
        @input="(e) => {
          const target = e.target as HTMLDivElement;
          if (target && target.innerHTML !== undefined) {
            editorContent = target.innerHTML;
          }
        }"
      ></div>
    </div>
    
    <div class="editor-footer">
      <button class="export-pdf-btn" @click="exportToPDF">导出PDF</button>
      <div class="footer-right-buttons">
        <!-- <button class="save-btn" @click="saveContent">保存</button> -->
        <button class="cancel-btn" @click="closeEditor">取消</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.editor-container {
  position: fixed;
  top: 0;
  right: -500px;
  width: 500px;
  height: 100vh;
  background-color: white;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 1000;
  transition: right 0.3s ease;
}

.editor-container.visible {
  right: 0;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.editor-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
}

.toolbar {
  padding: 8px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.toolbar-group {
  display: flex;
  gap: 4px;
  border-right: 1px solid #e5e7eb;
  padding-right: 8px;
  margin-right: 4px;
}

.toolbar-group:last-child {
  border-right: none;
}

.toolbar button {
  background: none;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 30px;
  height: 30px;
}

.toolbar button:hover {
  background-color: #f3f4f6;
}

.format-icon {
  font-style: normal;
}

.format-icon.bold {
  font-weight: bold;
}

.format-icon.italic {
  font-style: italic;
}

.format-icon.underline {
  text-decoration: underline;
}

.format-icon.strikethrough {
  text-decoration: line-through;
}

.editor-content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.editor-content {
  min-height: 100%;
  outline: none;
  padding: 8px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}

.editor-footer {
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-right-buttons {
  display: flex;
  gap: 12px;
}

.save-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #2563eb;
}

.cancel-btn {
  background-color: #f3f4f6;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e5e7eb;
}

.export-pdf-btn {
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
}

.export-pdf-btn:hover {
  background-color: #059669;
}

.export-pdf-btn:before {
  content: "📄";
  font-size: 16px;
}
</style>

<style>
/* 确保编辑器内容区域继承Markdown样式 */
.editor-content.markdown-body {
  line-height: 1.6;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}

.editor-content.markdown-body p {
  margin: 0.8em 0;
}

.editor-content.markdown-body h1,
.editor-content.markdown-body h2,
.editor-content.markdown-body h3,
.editor-content.markdown-body h4,
.editor-content.markdown-body h5,
.editor-content.markdown-body h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
}

.editor-content.markdown-body h1 {
  font-size: 2em;
}

.editor-content.markdown-body h2 {
  font-size: 1.5em;
}

.editor-content.markdown-body h3 {
  font-size: 1.25em;
}

.editor-content.markdown-body ul,
.editor-content.markdown-body ol {
  padding-left: 2em;
  margin: 1em 0;
}

.editor-content.markdown-body li {
  margin: 0.5em 0;
}

.editor-content.markdown-body pre {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow: auto;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 85%;
  line-height: 1.45;
  margin: 1em 0;
}

.editor-content.markdown-body code {
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 85%;
  padding: 0.2em 0.4em;
}

.editor-content.markdown-body pre code {
  background-color: transparent;
  padding: 0;
}

.editor-content.markdown-body blockquote {
  border-left: 0.25em solid #dfe2e5;
  color: #6a737d;
  padding: 0 1em;
  margin: 1em 0;
}

.editor-content.markdown-body table {
  border-collapse: collapse;
  width: 100%;
  margin: 1em 0;
}

.editor-content.markdown-body table th,
.editor-content.markdown-body table td {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
}

.editor-content.markdown-body table th {
  background-color: #f6f8fa;
  font-weight: 600;
}

.editor-content.markdown-body a {
  color: #0366d6;
  text-decoration: none;
}

.editor-content.markdown-body a:hover {
  text-decoration: underline;
}

.editor-content.markdown-body img {
  max-width: 100%;
  box-sizing: border-box;
}
</style>